﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BOMS.Model;
using BOMS.DAL;
using BOMS.Utility;
using System.Text;
using System.Web.SessionState;
using System.Data;
using System.Web.UI;

namespace BOMS.WebUI.Web
{
    public class Common 
    {
        /// <summary>
        /// 获取时间差HH:SS
        /// </summary>
        /// <returns></returns>
        public static string GetSpanTime(DateTime dt1, DateTime dt2)
        {
            TimeSpan ts = dt1 - dt2;
            if (ts <= new TimeSpan(0, 0, 0))
            {
                ts = new TimeSpan(0, 0, 0);
            }
            string ret = "";
            if (ts.Days > 0)
            {
                ret = string.Format("{0}天 {1:00}:{2:00}", ts.Days, ts.Hours, ts.Minutes);
            }
            else
            {
                ret = string.Format("{0:00}:{1:00}", ts.Hours, ts.Minutes);
            }
            return ret;
        }

        /// <summary>
        /// 获取当前系统用户的（中文）姓名
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentUserNameChz()
        {           
            DataRow dr;
            if (HttpContext.Current.Session["USERINFO_ROW"] == null)
            {
                string UserID = HttpContext.Current.User.Identity.Name;
                dr = SysAdmin.getUserInfoById(UserID).Rows[0];
                //保存用户信息到Session
                HttpContext.Current.Session["USERINFO_ROW"] = dr;
            }
            dr = (DataRow)HttpContext.Current.Session["USERINFO_ROW"];
            return dr["name"].ToString();
        }
        /// <summary>
        /// 获取ROOT节点名称
        /// </summary>
        /// <returns></returns>
        public static string GetHostName()
        {
            string str_Sql = "select * from sysParameter";
            DataTable dt = DBUtility.DbHelper.Rt_Table(str_Sql);
            return dt.Rows[0]["lanName"].ToString();
        }

        /// <summary>
        /// 刷新间隔
        /// </summary>
        public static readonly int RefreshIntev = 30000;// 暂时注释掉。liangning 2012/12/31. //SysAdmin.getRefreshInterval() * 1000;
        /// <summary>
        /// 电池代别（第2代）
        /// </summary>
        public const int GENRATION_NUM=2;

        public static void GoMsgPage(string msg, MsgState state, string backUrl)
        {
            string URL = string.Format("/web/Message.aspx?msg={0}&type={1}&backurl={2}",
            HttpUtility.UrlEncode(msg), state.ToString(), HttpUtility.UrlEncode(backUrl));
            HttpContext.Current.Response.Redirect(URL);
        }

        public static void Alert(Page page, String msg)
        {
            ScriptManager.RegisterStartupScript(page, page.GetType(), "aspnetalertmsg", "alert('" + msg + "');", true);
        }

        #region 报警状态字符串获取
        /// <summary>
        /// 警报状态的逻辑处理(特殊加工后，用于显示)
        /// </summary>
        /// <typeparam name="T">电池警报枚举，或电池组警报枚举</typeparam>
        /// <param name="WarningNO">警报数字</param>
        /// <returns></returns>
        public static int WarningNOLogicalDealwith<T>(int WarningNO) where T : struct, IComparable, IFormattable, IConvertible
        {
            if (typeof(T) == typeof(BatteryErrorStatus))//电池
            {
                if ((WarningNO & (int)BatteryErrorStatus.通讯超时) == (int)BatteryErrorStatus.通讯超时)
                {
                    //通讯超时,其它状态无效
                    WarningNO = (int)BatteryErrorStatus.通讯超时;

                }
                else if ((WarningNO & (~(int)BatteryErrorStatus.均衡)) != 0)
                {
                    //均衡时，若还有其它报警项,则忽略均衡本身
                    WarningNO = WarningNO & (~(int)BatteryErrorStatus.均衡);
                }
            }
            return WarningNO;
        }
        /// <summary>
        /// 构建警报提示字符串
        /// </summary>
        /// <typeparam name="T">电池警报枚举，或电池组警报枚举</typeparam>
        /// <param name="WarningNO">警报状态字</param>
        /// <param name="WithImage">是否输出中包含图片</param>
        /// <returns></returns>
        public static string BuildWarningString<T>(int WarningNO, bool WithImage) where T : struct, IComparable, IFormattable, IConvertible
        {
            StringBuilder sb = new StringBuilder();
            WarningNO = WarningNOLogicalDealwith<T>(WarningNO);//逻辑处理

            List<EnumUtility<T>.EnumInfo> Enumlist = EnumUtility<T>.GetEnumList();
            if (WarningNO != 0)//排除0状态的检查
            {
                for (int i = 0; i < Enumlist.Count; i++)
                {

                    //逐个按位检查，是否有某类型警报
                    if (Enumlist[i].Value != 0 && //排除0状态
                        (WarningNO & Enumlist[i].Value) == Enumlist[i].Value
                    )
                    {
                        sb.Append(CreImageItem(WithImage ? Enumlist[i].Descr : "", Enumlist[i].Item));
                    }

                }
            }
            else
            {
                sb.Append(CreImageItem(Enumlist[0].Descr, Enumlist[0].Item));//取0状态的图片和描述
            }

            return sb.ToString().TrimEnd(',');
        }
         /// <summary>
        /// 构建警报提示字符串
        /// </summary>
        /// <typeparam name="T">电池警报枚举，或电池组警报枚举</typeparam>
        /// <param name="WarningNO">警报状态字</param>
        /// <returns></returns>
        public static string BuildWarningString<T>(int WarningNO) where T : struct, IComparable, IFormattable, IConvertible
        {
            return BuildWarningString<T>(WarningNO, false);
        }
        /// <summary>
        /// 构建警报提示字符串
        /// </summary>
        /// <param name="IsGroup">是否电池组</param>
        /// <param name="WarningNO">报警编号字</param>
        /// <param name="WithImage">是否包含提示图标</param>
        /// <returns></returns>
        public static string BuildWarningString(bool IsGroup,int WarningNO,bool WithImage)
        {
            if (IsGroup)
            {
                return BuildWarningString<GroupErrorStatus>(WarningNO, WithImage);
            }
            else
            {
                return BuildWarningString<BatteryErrorStatus>(WarningNO, WithImage);
            }
        }
        /// <summary>
        /// 构建警报提示字符串(默认不包含小图标)
        /// </summary>
        /// <param name="IsGroup">是否电池组</param>
        /// <param name="WarningNO">报警编号字</param>       
        public static string BuildWarningString(bool IsGroup, int WarningNO)
        {
            return BuildWarningString(IsGroup, WarningNO, false);
        }
        /// <summary>
        /// 根据警报枚举类型和图片名称，返回一个含图片的html字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="src">图片名称</param>
        /// <param name="stat">警报状态枚举</param>
        /// <returns></returns>
        private static string CreImageItem<T>(string src, T stat) where T : struct, IComparable, IFormattable, IConvertible
        {
            if (string.IsNullOrEmpty(src))
            {
                return stat.ToString()+",";//枚举的名称
            }
            else
            {
                return string.Format("<img style='vertical-align:middle;margin-right:5px;' src='/Images/{0}' />{1}", src, stat.ToString());
            }
        }
        #endregion
        /// <summary>
        /// 构建是否在线的图片显示
        /// </summary>
        /// <param name="Onlinestatus"></param>
        /// <returns></returns>
        public static string BuildIsOnlineString(OnlineStatus Onlinestatus)
        {
            string ImgName = Onlinestatus.ToDescription();
            if (string.IsNullOrEmpty(ImgName))
            {
                return Onlinestatus.ToString();
            }
            else
            {
                return string.Format("<img style='vertical-align:middle;margin-right:5px;' src='/Images/{0}' />{1}", ImgName, Onlinestatus.ToString());
            }
        }
    }
}